<template>
    <div class="app-container">
        <levelbar></levelbar>
        <div class="form-box">
            <div class="form-title">修改经销商</div>
            <el-form label-width="100px" class="app-content form" :rules="rules" :model="ruleForm" ref="ruleForm">
                <div class="form-item">
                    <div class="form-item-title">
                        <span class="title-level">经销商信息</span>
                    </div>
                    <div class="form-content">
                        <el-row :gutter="21">               
                            <el-col :span="12">
                                <el-form-item label="用户名" prop="account">
                                    <el-popover placement="top-start" trigger="focus" content="字符长度不大于30个"> 
                                        <el-input v-model="ruleForm.account" placeholder="请输入用户名" :maxlength="30" slot="reference" style="width:95%"></el-input>
                                    </el-popover>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="负责人" prop="userName">
                                    <el-popover placement="top-start" trigger="focus" content="字符长度不大于30个"> 
                                        <el-input v-model="ruleForm.userName" placeholder="请输入负责人姓名" :maxlength="30" slot="reference" style="width:95%"></el-input>
                                    </el-popover>
                                </el-form-item>
                            </el-col>
                        </el-row>      
                        <el-row :gutter="21">  
                            <el-col :span="12">
                                <el-form-item label="手机号" prop="phone">
                                    <el-popover placement="top-start" trigger="focus" content="字符长度不大于11个">
                                        <el-input v-model="ruleForm.phone" placeholder="请输入手机号" :maxlength="11" slot="reference" style="width:95%"></el-input>
                                    </el-popover>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </div>
                    <div class="form-item-title">
                        <span class="title-level">代理信息</span>
                    </div>
                    <div class="form-content">
                        <el-row :gutter="21">
                            <el-col :span="12">
                                <el-form-item label="代理金额" prop="agentMoney">
                                    <el-popover placement="top-start" trigger="focus" content="字符长度不大于9个">
                                        <el-input v-model="ruleForm.agentMoney" placeholder="请输入代理金额" auto-complete="off" :maxlength="9" slot="reference" style="width:95%"></el-input>
                                    </el-popover>
                                </el-form-item>
                            </el-col>      
                            <el-col :span="12">
                                <el-form-item label="代理学校数" prop="schoolNum">
                                    <el-popover placement="top-start" trigger="focus" content="代理学校数不超过99个">
                                        <el-input v-model="ruleForm.schoolNum" placeholder="请输入代理学校数" auto-complete="off" :maxlength="2" slot="reference" style="width:95%"></el-input>
                                    </el-popover>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </div>
                    <div class="form-item-title">
                        <span class="title-level">负责区域</span>
                    </div>
                    <div class="form-content">
                        <el-row v-for="(site,index) in ruleForm.dataAgent" class="areaBoxcon" v-bind:class="{ 'area-first': index==0 }" :key="site.key">
                            <el-row :gutter='21'>
                                <el-col :span="7">
                                    <el-form-item label="所选省：" :prop="'dataAgent.' + index + '.fProvinceId'" 
                                    :rules="{required: true, message: '所选省不能为空', trigger: 'change'}">
                                        <province v-model="site.fProvinceId"></province>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="7" :offset="1">
                                    <el-form-item label="所选市：">
                                        <city v-model="site.fCityId" :province="site.fProvinceId"></city>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="7" :offset="1">
                                    <el-form-item label="所选区县：">
                                        <region v-model="site.fAreaId" :city="site.fCityId"></region>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="1" v-if="index != 0">
                                    <el-button type="text" class="delBtn" @click.prevent="removeDomain(index)"><i class="el-icon-delete"></i></el-button>
                                </el-col>
                            </el-row>
                        </el-row>
                        <el-button type="text" @click="addArea" class="addBtn btn-success" v-if="ruleForm.dataAgent.length<5"><i class="el-icon-plus"></i> 继续添加</el-button>
                    </div>
                </div>
                <div class="form-item">
                    <div class="footer">
                        <el-button @click="resetForm">取消</el-button>
                        <el-button type="primary" @click="submitForm('ruleForm')" :loading="loadingBtn">确认</el-button>
                    </div>
                </div>
            </el-form>
        </div>
    </div>
</template>
 
<script>
import Levelbar from '../layout/Levelbar';
import { findAgentAreaByOrgUserId, findAccountIsExist, saveAgentArea, getOrgUserSchoolMapById} from 'api/agentMangement';
import startDate from 'components/Datepicker/startDate';
import endDate from 'components/Datepicker/endDate';
import province from 'components/CascadeRegion/province';
import city from 'components/CascadeRegion/city';
import region from 'components/CascadeRegion/region';
import validate from '@/utils/validate';
export default{
    name: 'reviseAgent',
    components: { Levelbar, startDate, endDate, province, city, region},
    data() {
        // 登录名判断重复
        var loginUserName = (rule, value, callback) => {
            if (value =='') {
                callback(new Error('请输入用户名'));
            } else if (value != this.ruleForm.accountFake) {
                if (value.indexOf(' ') == -1) {
                    findAccountIsExist(value).then(res => {
                        callback();
                    }).catch(e => {
                        callback(new Error('用户名已存在'));
                    }) 
                } else {
                    callback(new Error('请勿输入空格'));
                }
            } else {
                callback();
            }
            
        };
        return { 
            ruleForm: {
                account: '', // 账号
                userName: '', // 负责人姓名
                phone: '',
                accountFake: '',
                orgUserId: '', // 经销商id
                findCity: [],
                findArea: [],
                findProvice: [],
                dataAgent: [], // 全部数据
                schoolNum: '',
                agentMoney: ''
            },
            delOrgRegionMaps: [],
            loadingBtn: false,
            rules: {
                account: [
                    { required: true, validator: loginUserName, trigger: 'blur' },
                    { pattern: /^[^ ]+$/, message: '请勿输入空格', trigger: 'change'}
                ],
                userName: [
                    { required: true, message: '请输入负责人姓名', trigger: 'blur' },
                    { pattern: /^[^ ]+$/, message: '请勿输入空格', trigger: 'change'}
                ],
                phone: [...validate.phoneRequired()],
                agentMoney: [
                    { required: true, message: '请输入代理金额', trigger: 'blur' },
                    { pattern: /^[0-9]\d*$/, message: '代理金额最低为0元，且为整数', trigger: 'blur'}
                ],
                schoolNum: [
                    { required: true, message: '请输入代理学校数量', trigger: 'blur' },
                    { pattern: /^[1-9]\d*$/, message: '代理学校数量最低为1', trigger: 'blur'}
                ]
            }
 
        }
    },
    created() {
        this.create();
        this.searchTerritory();
        this.searchSchoolNum();
    },
    methods: {
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let areaList = this.ruleForm.dataAgent.map(item => {
                        return item.fProvinceId+item.fCityId+item.fAreaId;
                    })
                    for (let i = 0;i<areaList.length;i++) {
                        var arrList = [];
                        for (let j = 0;j<areaList.length;j++) {
                            arrList[j] = areaList[j];
                        }
                        arrList.splice(i, 1);
                        if (arrList.indexOf(areaList[i])>-1) {
                            this.$message({
                                type: 'error',
                                message: '代理区域重复'
                            });
                            return;
                        }
                    }
                    this.$confirm('确定要提交吗?', '', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消'
                    }).then(() => {
                        var dataAgentList = []
                        for (let i = 0;i< this.ruleForm.dataAgent.length;i++) {
                            let obj = {
                                pId: this.ruleForm.dataAgent[i].pId,
                                fOrgId: this.ruleForm.dataAgent[i].fOrgId,
                                fAgentType: this.ruleForm.dataAgent[i].fAgentType,
                                fProvinceId: this.ruleForm.dataAgent[i].fProvinceId,
                                fCityId: this.ruleForm.dataAgent[i].fCityId,
                                fAreaId: this.ruleForm.dataAgent[i].fAreaId
                            }
                            dataAgentList.push(obj)
                        }
                        this.loadingBtn = true;
                        saveAgentArea(
                        this.ruleForm.orgUserId,
                        this.ruleForm.userName,
                        this.ruleForm.account,
                        this.ruleForm.phone,
                        dataAgentList,
                        this.delOrgRegionMaps,
                        this.ruleForm.schoolNum,
                        this.ruleForm.agentMoney,
                        this.ruleForm.orgUserId
                        ).then(response => {
                            this.$message({
                                type: 'success',
                                message: '修改经销商成功!'
                            })
                            this.loadingBtn = false;
                            this.$store.dispatch('UpdateCache', true);// 修改 和查看
                            this.$router.push({path: '/agentManagement'});
                        }).catch(() => {
                            this.loadingBtn = false;
                        });
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消'
                        });
                    });
                } else {
                    return false;
                }
            });
        },
        // 拆分传过来的字符串
        create() {
            let arrList = this.$route.params.agentId.split(',');
            this.ruleForm.orgUserId = arrList[0];
            this.ruleForm.account = arrList[1];
            this.ruleForm.accountFake = arrList[1];
            this.ruleForm.phone = arrList[2];
            this.ruleForm.userName = arrList[3];
        },
 
        // 查询代理区域
        searchTerritory() {
            findAgentAreaByOrgUserId(this.ruleForm.orgUserId).then(response => {
                for (let i = 0;i < response.data.content.length;i++) {
                    let area = {
                        pId: response.data.content[i].pId,
                        fOrgId: response.data.content[i].fOrgId,
                        fAgentType: response.data.content[i].fAgentType,
                        findCity: '',
                        findArea: '',
                        fProvinceId: response.data.content[i].fProvinceId,
                        fCityId: response.data.content[i].fCityId,
                        fAreaId: response.data.content[i].fAreaId
                    };
                    this.ruleForm.dataAgent.push(area);
                    this.$nextTick(() => {
                        area.fProvinceId = response.data.content[i].fProvinceId;
                        this.$nextTick(() => {
                            area.fCityId = response.data.content[i].fCityId;
                            this.$nextTick(() => {
                                area.fAreaId = response.data.content[i].fAreaId;
                            });
                        });
                    });
                    // this.dateChange1(area.sAgentStartDate, i);
                    // this.dateChange2(area.sAgentEndDate, i);
                }
            });
        },
        searchSchoolNum() {
            getOrgUserSchoolMapById(this.ruleForm.orgUserId).then(res => {
                this.ruleForm.schoolNum = res.data.content.sSchoolNum.toString();
                this.ruleForm.agentMoney = res.data.content.sMoney.toString();
            })
        },
       // 添加区域
        addArea() {
            if (this.ruleForm.dataAgent.length>4) {
                this.$message.warning('最多可以添加5个区域');
                return;
            }
            let area = {
                fAgentType: '3',
                fProvinceId: '',
                fCityId: '',
                fAreaId: '',
                sAgentPrice: '',
                sAgentStartDate: '',
                sAgentEndDate: '',
                findCity: '',
                findArea: '',
                pId: '',
                pickerOptions1: {},
                pickerOptions2: {}
            };
            this.ruleForm.dataAgent.push(area)
        },
        removeDomain(index) {
            this.$confirm('确定要删除这个区域吗?', ' ', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'            
            }).then(() => {
                if (this.ruleForm.dataAgent[index].pId) {
                    this.delOrgRegionMaps.push(this.ruleForm.dataAgent[index].pId);
                }
                this.ruleForm.dataAgent.splice(index, 1);
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
            
        },
        resetForm() {
            this.$router.push({path: '/agentManagement'});
        }
    }
}
</script>
 
<style lang="scss" scoped>
.app-container {
  position: relative;
  padding: 20px 20px 10px;
  $bgcolor: #fff;
 
  @mixin showTitle() {
    background: $bgcolor;
    box-shadow:  0px 0px 5px 0px rgba(0, 0, 0, 0.1);
    -webkit-box-shadow:  0px 0px 5px 0px rgba(0, 0, 0, 0.1);
  }
  .form-box {
    padding: 0 50px;
    @include showTitle();
    .form-title {
      padding-top:8px;
      text-align: center;
      font-size: 18px;
      color: #333;
      line-height: 72px;
      font-weight: bold;
      font-family: Microsoft YaHei;
      border-bottom: 1px solid #ddd;
    }
    .form {
      .form-content{
          padding-bottom: 40px;
      }
      .form-item {
        padding-bottom: 40px;
        .form-item-title {
            margin: 40px 0;
            font-size: 14px;
            color: #333;
            line-height: 14px;
            border-left: 4px solid #ff5e2c;
            text-indent: 16px;
           
          .note-css {
            vertical-align: middle;
            display: inline-block;
            width: 4px;
            height: 14px;
            margin-right: 26px;
            border-left: 3px solid #ff5e2c;
          }
          
        }
        .footer {
          text-align: center;
          margin-top: 40px;
        }
        .delBtn {
            font-size: 20px;
            color:#999;
        }
        .areaBoxcon{
            margin-top:40px;
        }
        .area-first{
            margin-top:0 !important;
        }
        .addBtn{
            margin-left:100px;
            font-size:14px;
            color:#ff5e2c;
        }
      }
    }
  }
}
 
</style>